#!/usr/bin/perl
# 2014/02/05 backgroundの比をchrIとchrIIのreadsの比で出す

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;


if(@ARGV != 6 or $ARGV[0] eq '--help'){
	die "Usage : $0 -s [sample directory] -c [control directory] -o [background ratio]\n";
}


my %opt;
getopts("s:c:o:", \%opt);
my $DIR_sample = $opt{s};
my $DIR_control = $opt{c};
my $FILE_output = $opt{o};

my $SUM_sample = &readMap($DIR_sample);
my $SUM_control = &readMap($DIR_control);
sub readMap{
	my ($directory) = @_;
	my $total = 0;
	foreach my $chr(qw(I II)){
	    my $file = sprintf "%s/%s.tags.tsv", $directory, $chr;
		my $fh = IO::File->new($file) or die "cannot open $file: $!";
		while($_ = $fh->getline()){
			s/\r?\n//;
			### TSV format
			my ($none, $chr, $pos, $direction, $tags, $length) = split /\t/;
			$total += $tags;
		}
		$fh->close();
	}
	return $total;
}


### calculate reads in each window
my $fh_out = IO::File->new($FILE_output, 'w') or die "cannot write $FILE_output: $!";
my $ratio = $SUM_sample / $SUM_control;
$fh_out->print("$ratio\n");
$fh_out->close();
